var express = require('express');
var router = express.Router();
var pool = require('../config/mysqlconfig');
const jwt = require('jsonwebtoken');
// http://localhost:3000/login/login
router.post('/login',function(req,res){
    let username = req.body.username;
    let password = req.body.password;
    pool.getConnection(function(err,conn){
        if(err){
            console(err);
            console.log("数据库连接失败")
            // conn.release()
        }else{      
            console.log("数据库连接成功");
            let data = [username,password];
            let sql = "select * from admin where username=? and password=?";          
            conn.query(sql,data,function(error,results){
                if(error){
                   
                    console.log(error)
                   
                }
                if(results.length != 0){
                    const payload = {
                        name:results.username
                    }
                    const secret = "deyun"                  
                    const token = jwt.sign(payload,secret,{
                        expiresIn:'10s'});                  
                    res.json({
                        success:true,
                        message:"Enjoy your token",
                        token:token
                    })
                }   
                // res.send("...")
                // res.send(null)
                conn.release();

            })
        }
    })
}),

router.post('/add',function(req,res){
    pool.getConnection(function(err,conn){
        if(err){
            console.log("数据库链接失败")
        }else{
            let username = req.body.username;
            let passwords = req.body.password;
            

            let sql = "insert into admin set ?"
            let data = {
                username:username,
                password:passwords,
                
            }
            conn.query(sql,data,function(error,results){
                if(error){
                    console.log(error)
                    return
                }
                // if(results){
                //     // res.redirect('all')

                // }
                res.send(results)
                conn.release()
            })
        }
    })
})


module.exports = router